import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;

import LunaServer.config.ConfigManager;
import LunaServer.core.LunaServer;
import LunaServer.routing.Route;
import LunaServer.email.EmailService;
import LunaServer.util.VerificationCodeManager;
import LunaServer.logging.*;

/**
 * 邮箱验证码路由处理器
 * 处理/send-verification-code和/verify-code路径的请求
 */
public class EmailVerificationRoute implements Route {
    private final LunaServer server;
    private final EmailService emailService;
    private final Logger logger = Logger.getInstance();

    public EmailVerificationRoute(LunaServer server) {
        this.server = server;
        // 从文件中读取配置。
        Gson gson = new Gson();

        // 初始化邮件服务（示例配置，请根据实际邮件服务提供商修改）
        this.emailService = new EmailService(
                "smtp.gmail.com", // SMTP服务器地址
                "587", // SMTP端口
                "lunaticlegacy9@gmail.com", // 邮箱用户名
                "xsmtpsib-d8c8010fda0111d112dcd6f6aac2dd3caab4999b69d3fcef7925b087625cc0d5-0rpDB2F3UajxzqM9", // 邮箱密码或授权码
                "noreply@luna.com" // 发件人地址
        );
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        String response = "";
        int responseCode = 200;

        String path = exchange.getRequestURI().getPath();

        if ("POST".equals(exchange.getRequestMethod())) {
            if ("/send-verification-code".equals(path)) {
                // 如果请求为发送验证码
                response = handleSendVerificationCode(exchange);
            } else if ("/verify-code".equals(path)) {
                // 如果请求为验证验证码
                response = handleVerifyCode(exchange);
            } else {
                // 未知路径
                handleNotFound(exchange);
            }
        } else {
            handleMethodNotAllowed(exchange);
        }

        // 发送响应
        exchange.sendResponseHeaders(responseCode, response.getBytes(StandardCharsets.UTF_8).length);
        return response;
    }

    /**
     * 处理发送验证码请求
     */
    private String handleSendVerificationCode(HttpExchange exchange) throws IOException {
        try {
            // 读取请求体
            String requestBody = "";
            try (InputStream is = exchange.getRequestBody()) {
                requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            }

            // 解析数据
            Gson gson = new Gson();
            Map<String, String> requestData = gson.fromJson(requestBody, Map.class);

            String email = requestData.get("email");

            if (email == null || email.isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", "400");
                errorResult.put("error", "邮箱地址不能为空");
                errorResult.put("time", Instant.now().toString());
                exchange.getResponseHeaders().set("Content-Type", "application/json");
                return gson.toJson(errorResult);
            }

            // 生成并存储验证码
            String verificationCode = VerificationCodeManager.generateAndStoreCode(email, 6);

            // 发送邮件
            boolean emailSent = emailService.sendVerificationCode(email, verificationCode);

            Map<String, Object> responseMap = new HashMap<>();
            if (emailSent) {
                responseMap.put("code", "200");
                responseMap.put("message", "验证码已发送到您的邮箱");
            } else {
                responseMap.put("code", "500");
                responseMap.put("error", "验证码发送失败，请稍后重试");
            }
            responseMap.put("time", Instant.now().toString());
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            return gson.toJson(responseMap);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", "400");
            errorResult.put("error", "Invalid JSON format");
            errorResult.put("time", Instant.now().toString());
            Gson gson = new Gson();
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            return gson.toJson(errorResult);
        }
    }

    /**
     * 处理验证验证码请求
     */
    private String handleVerifyCode(HttpExchange exchange) throws IOException {
        try {
            // 读取请求体
            String requestBody = "";
            try (InputStream is = exchange.getRequestBody()) {
                requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            }

            // 解析数据
            Gson gson = new Gson();
            Map<String, String> requestData = gson.fromJson(requestBody, Map.class);

            String email = requestData.get("email");
            String code = requestData.get("code");

            if (email == null || email.isEmpty() || code == null || code.isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", "400");
                errorResult.put("error", "邮箱地址和验证码不能为空");
                errorResult.put("time", Instant.now().toString());
                exchange.getResponseHeaders().set("Content-Type", "application/json");
                return gson.toJson(errorResult);
            }

            // 验证验证码
            VerificationCodeManager.VerificationResult result = VerificationCodeManager.verifyCode(email, code);

            Map<String, Object> responseMap = new HashMap<>();
            if (result.isValid) {
                responseMap.put("code", "200");
                responseMap.put("message", "验证码验证成功");
            } else {
                responseMap.put("code", "400");
                responseMap.put("error", result.message);
            }
            responseMap.put("time", Instant.now().toString());
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            return gson.toJson(responseMap);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", "400");
            errorResult.put("error", "Invalid JSON format");
            errorResult.put("time", Instant.now().toString());
            Gson gson = new Gson();
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            return gson.toJson(errorResult);
        }
    }
}